<style></style>

<div id="customOrderForm">
    <!-- 自定义发单按钮 -->
    <button class="layui-btn layui-btn-normal" id="customOrderBtn">自定义发单</button>
</div>

<!-- 自定义发单模态框 -->
<div id="customOrderModal" style="display: none; padding: 20px;">
    <form class="layui-form" lay-filter="customOrderForm">
        <div class="layui-form-item">
            <label class="layui-form-label">订单标题</label>
            <div class="layui-input-block">
                <input type="text" name="title" id="customTitle" lay-verify="required" placeholder="请输入订单标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">订单金额</label>
            <div class="layui-input-block">
                <input type="text" name="amount" id="customAmount" lay-verify="required|number" placeholder="请输入订单金额" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">安全保证金</label>
            <div class="layui-input-block">
                <input type="text" name="securityDeposit" id="customSecurityDeposit" lay-verify="required|number" placeholder="请输入安全保证金" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">效率保证金</label>
            <div class="layui-input-block">
                <input type="text" name="efficiencyDeposit" id="customEfficiencyDeposit" lay-verify="required|number" placeholder="请输入效率保证金" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">时间要求(小时)</label>
            <div class="layui-input-block">
                <input type="text" name="hour" id="customHour" lay-verify="required|number" placeholder="请输入时间要求" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">游戏区服名称</label>
            <div class="layui-input-block">
                <input type="text" name="gameRegionName" id="customGameRegionName" placeholder="请输入游戏区服名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">游戏</label>
            <div class="layui-input-block">
                <input type="text" name="game" id="customGame" placeholder="请输入游戏名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">区服</label>
            <div class="layui-input-block">
                <input type="text" name="zone" id="customZone" placeholder="请输入区服" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">服务器</label>
            <div class="layui-input-block">
                <input type="text" name="server" id="customServer" placeholder="请输入服务器" autocomplete="off" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item" style="text-align: center;">
            <button class="layui-btn" lay-submit lay-filter="submitCustomOrder">提交订单</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="closeCustomOrderModal()">取消</button>
        </div>
    </form>
</div>

<script>
    // 关闭自定义发单模态框
    function closeCustomOrderModal() {
        layer.closeAll();
    }
</script>

<script>
    layui.use(['layer', 'form'], function () {
        var $ = layui.$;
        var layer = layui.layer;
        var form = layui.form;
        
        // 存储代练丸子余额
        var wanziBalance = 0;
        
        /**
         * 打开自定义发单模态框
         */
        $(document).on('click', '#customOrderBtn', function() {
            // 先检查是否已查询余额
            if (wanziBalance === 0) {
                layer.confirm('尚未查询代练丸子余额，发单前必须先查询余额，是否现在查询？', {
                    btn: ['是', '否'],
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    
                    // 查询余额
                    getWanziBalance().then(function() {
                        if (wanziBalance > 0) {
                            openCustomOrderModal();
                        } else {
                            layer.msg('余额为0，无法进行发单', {icon: 5});
                        }
                    }).catch(function() {
                        layer.msg('余额查询失败，无法进行发单', {icon: 5});
                    });
                });
            } else {
                openCustomOrderModal();
            }
        });
        
        /**
         * 打开自定义发单模态框的具体实现
         */
        function openCustomOrderModal() {
            // 打开模态框
            layer.open({
                type: 1,
                title: '自定义发单',
                content: $('#customOrderModal'),
                area: ['600px', 'auto'],
                success: function() {
                    // 重新渲染表单
                    layui.form.render();
                    // 清空输入框
                    $('#customTitle').val('');
                    $('#customAmount').val('');
                    $('#customSecurityDeposit').val('');
                    $('#customEfficiencyDeposit').val('');
                    $('#customHour').val('');
                    $('#customGameRegionName').val('');
                    $('#customGame').val('');
                    $('#customZone').val('');
                    $('#customServer').val('');
                },
                end: function() {
                    // 隐藏模态框
                    $('#customOrderModal').hide();
                }
            });
        }
        
        /**
         * 获取代练丸子余额
         * @returns {Promise} - 返回Promise对象
         */
        function getWanziBalance() {
            return new Promise(function(resolve, reject) {
                // 显示加载中
                layer.load();
                
                // 调用获取余额API
                $.ajax({
                    url: '/api/dailianwanzi/get_my_balance/',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        // 隐藏加载中
                        layer.closeAll('loading');
                        
                        if (res.code === 0 && res.data && res.data.balance) {
                            wanziBalance = parseFloat(res.data.balance);
                            layer.msg('查询余额成功', {icon: 6});
                            resolve();
                        } else {
                            layer.msg('查询余额失败：' + (res.message || '未知错误'), {icon: 5});
                            reject();
                        }
                    },
                    error: function(xhr, status, error) {
                        // 隐藏加载中
                        layer.closeAll('loading');
                        
                        layer.msg('网络错误，无法查询余额', {icon: 5});
                        console.error('查询余额失败：', error);
                        reject();
                    }
                });
            });
        }
        
        /**
         * 提交自定义订单
         * @param {Object} formData - 表单数据
         * @returns {Promise} - 返回提交结果的Promise
         */
        function submitCustomOrder(formData) {
            // 显示加载中
            layer.load();
            
            // 调用发布订单API
            return $.ajax({
                url: '/api/dailianwanzi/publish_order/',
                type: 'GET',
                data: formData,
                dataType: 'json',
                success: function(res) {
                    // 隐藏加载中
                    layer.closeAll('loading');
                    
                    if (res.code === 0 && res.data && res.data.tradeNo) {
                        var tradeNo = res.data.tradeNo;
                        console.log('代练丸子发布成功，交易编号：', tradeNo);
                        
                        // 创建主订单
                        $.ajax({
                            url: '/api/order/create/',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({}),
                            dataType: 'json',
                            success: function(createRes) {
                                if (createRes.code === 0 && createRes.data && createRes.data.order_id) {
                                    var orderId = createRes.data.order_id;
                                    
                                    // 创建代练丸子子订单，订单编号使用服务器返回的tradeNo
                                    createSubOrderWithName(orderId, '代练丸子', tradeNo);
                                    
                                    layer.msg('自定义发单成功', {icon: 6});
                                    closeCustomOrderModal();
                                } else {
                                    console.error('创建订单失败：', createRes.message);
                                    layer.msg('创建订单失败：' + (createRes.message || '未知错误'), {icon: 5});
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('创建订单失败：', error);
                                layer.msg('创建订单失败：' + error, {icon: 5});
                            }
                        });
                    } else {
                        layer.msg('发布订单失败：' + (res.message || '未知错误'), {icon: 5});
                    }
                },
                error: function(xhr, status, error) {
                    // 隐藏加载中
                    layer.closeAll('loading');
                    
                    layer.msg('网络错误，无法发布订单', {icon: 5});
                    console.error('发布订单失败：', error);
                }
            });
        }
        
        // 表单提交处理
        form.on('submit(submitCustomOrder)', function(data) {
            // 获取表单数据
            var formData = data.field;
            
            // 验证表单数据
            if (!formData.title || formData.title.trim() === '') {
                layer.msg('请输入订单标题', {icon: 5});
                return false;
            }
            
            if (!formData.amount || isNaN(parseFloat(formData.amount)) || parseFloat(formData.amount) <= 0) {
                layer.msg('请输入有效的订单金额', {icon: 5});
                return false;
            }
            
            if (!formData.securityDeposit || isNaN(parseFloat(formData.securityDeposit)) || parseFloat(formData.securityDeposit) < 0) {
                layer.msg('请输入有效的安全保证金', {icon: 5});
                return false;
            }
            
            if (!formData.efficiencyDeposit || isNaN(parseFloat(formData.efficiencyDeposit)) || parseFloat(formData.efficiencyDeposit) < 0) {
                layer.msg('请输入有效的效率保证金', {icon: 5});
                return false;
            }
            
            if (!formData.hour || isNaN(parseInt(formData.hour)) || parseInt(formData.hour) <= 0) {
                layer.msg('请输入有效的时间要求', {icon: 5});
                return false;
            }
            
            // 检查余额是否足够
            if (parseFloat(formData.amount) > wanziBalance) {
                layer.msg('余额不足，无法发布订单', {icon: 5});
                return false;
            }
            
            // 提交订单
            submitCustomOrder(formData);
            
            return false; // 阻止表单跳转
        });
        
        // 导出函数，以便其他页面调用
        window.openCustomOrderModal = openCustomOrderModal;
    });
</script>